import { AppDataSource } from "./data-source";
import { City } from "./entity/City";

AppDataSource.initialize()
	.then(async () => {
        const entityManager = AppDataSource.manager;

        // 初始化
		// await entityManager.save(city);
		// const cityChild = new City();
		// cityChild.name = "山东";
		// const parent = await entityManager.findOne(City, {
		// 	where: {
		// 		name: "华北",
		// 	},
		// });
		// if (parent) {
		// 	cityChild.parent = parent;
		// }
		// await entityManager.save(City, cityChild);


        // 添加children  先找parent
		// const city = new City();
		// city.name = "青岛";
        // const parent = await entityManager.findOne(City , {
        //     where:{name:"山东"}
        // })
        // if(parent){
        //     city.parent = parent
        // }
        // await entityManager.save(City , city)

        // 返回树结构
        const treeRes = await entityManager.getTreeRepository(City).findTrees();
		console.log("treeRes" , treeRes);
        console.log(treeRes.map(item => item.children));

        console.log('---------------------------------------------');
        

        // 返回根节点
        const parentRes = await entityManager.getTreeRepository(City).findRoots()
        console.log("parentRes", parentRes);
        
        // findDescendantsTree 是查询某个节点的所有后代节点。
        // findAncestorsTree 是查询某个节点的所有祖先节点。
        // findAncestors findDescendants  find 就是用扁平结构返回：
        // countAncestors 和 countDescendants 来计数
        console.log('---------------------------------------------');
        console.log("findAncestors" , await entityManager.getTreeRepository(City).find());
        

	})
	.catch((error) => console.log(error));
